<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="类型" prop="type">
        <el-input
          v-model="queryParams.type"
          class="!w-240px"
          clearable
          placeholder="请输入类型"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="二级分类" prop="secondLevel">
        <el-input
          v-model="queryParams.secondLevel"
          class="!w-240px"
          clearable
          placeholder="请输入二级分类"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="三级分类" prop="thirdLevel">
        <el-input
          v-model="queryParams.thirdLevel"
          class="!w-240px"
          clearable
          placeholder="请输入三级分类"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button type="success" @click="handleInputPhysicalCard">
          <Icon class="mr-5px" icon="ep:upload" />
          实体卡录入
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="filterList">
      <el-table-column align="center" label="编号" min-width="80" prop="id" />
      <el-table-column align="center" label="类型" prop="type" min-width="100" />
      <el-table-column align="center" label="二级分类" prop="secondLevel" min-width="120" />
      <el-table-column align="center" label="三级分类" prop="thirdLevel" min-width="120" />
      <el-table-column align="center" label="库存" prop="stock" min-width="100">
        <template #default="{ row }">
          <span
            :class="{
              'text-red-500 font-bold':
                row.stockWarning !== null &&
                row.stockWarning !== undefined &&
                row.stock < row.stockWarning
            }"
          >
            {{ row.stock }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="库存预警" prop="stockWarning" min-width="100">
        <template #default="{ row }">
          <span v-if="row.stockWarning !== null && row.stockWarning !== undefined">{{
            row.stockWarning
          }}</span>
          <span v-else class="text-gray-400">未设置</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="status" min-width="100">
        <template #default="{ row }">
          <DictTag :type="DICT_TYPE.COMMON_STATUS" :value="row.status" />
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="价格" prop="price" min-width="100">
        <template #default="{ row }">
          ¥{{ row.price || 0 }}
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="图文详情" min-width="120">
        <template #default="{ row }">
          <el-button v-if="row.description" link type="primary" @click="handleViewDescription(row)">
            查看详情
          </el-button>
          <span v-else class="text-gray-400">暂无详情</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="440" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="primary" @click="handleViewDetail(row)">查看</el-button>
          <el-button link type="warning" @click="handleWarning(row)">预警设置</el-button>
          <el-button link type="success" @click="handleGenerateCard(row)">生成卡片</el-button>
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 编辑弹窗 -->
  <Dialog v-model="editVisible" title="编辑SKU库存" width="600px">
    <el-form ref="editFormRef" :model="editForm" label-width="100px">
      <el-form-item label="类型">
        <el-input v-model="editForm.type" readonly />
      </el-form-item>
      <el-form-item label="二级分类">
        <el-input v-model="editForm.secondLevel" readonly />
      </el-form-item>
      <el-form-item label="三级分类">
        <el-input v-model="editForm.thirdLevel" readonly />
      </el-form-item>
      <el-form-item label="库存">
        <el-input-number v-model="editForm.stock" :min="0" class="!w-full" />
      </el-form-item>
      <el-form-item label="价格">
        <el-input-number v-model="editForm.price" :min="0" :precision="2" class="!w-full" />
      </el-form-item>
      <el-form-item label="市场价">
        <el-input-number v-model="editForm.marketPrice" :min="0" :precision="2" class="!w-full" />
      </el-form-item>
      <el-form-item label="成本价">
        <el-input-number v-model="editForm.costPrice" :min="0" :precision="2" class="!w-full" />
      </el-form-item>
      <el-form-item label="图片">
        <UploadImg v-model="editForm.picUrl" />
      </el-form-item>
      <el-form-item label="图文详情">
        <Editor v-model="editForm.description" :height="300" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editVisible = false">取 消</el-button>
      <el-button type="primary" :loading="saving" @click="handleSave">保 存</el-button>
    </template>
  </Dialog>

  <!-- 详情弹窗 -->
  <Dialog v-model="detailVisible" title="SKU详情" width="700px">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="SKU编号">{{ detailData.id }}</el-descriptions-item>
      <el-descriptions-item label="SPU编号">{{ detailData.spuId }}</el-descriptions-item>
      <el-descriptions-item label="类型">{{ detailData.type }}</el-descriptions-item>
      <el-descriptions-item label="二级分类">{{ detailData.secondLevel }}</el-descriptions-item>
      <el-descriptions-item label="三级分类" :span="2">{{
        detailData.thirdLevel
      }}</el-descriptions-item>
      <el-descriptions-item label="库存">{{ detailData.stock }}</el-descriptions-item>
      <el-descriptions-item label="库存预警">
        <span v-if="detailData.stockWarning !== null && detailData.stockWarning !== undefined">{{
          detailData.stockWarning
        }}</span>
        <span v-else class="text-gray-400">未设置</span>
      </el-descriptions-item>
      <el-descriptions-item label="状态">
        <DictTag :type="DICT_TYPE.COMMON_STATUS" :value="detailData.status" />
      </el-descriptions-item>
      <el-descriptions-item label="价格">¥{{ detailData.price || 0 }}</el-descriptions-item>
      <el-descriptions-item label="市场价">¥{{ detailData.marketPrice || 0 }}</el-descriptions-item>
      <el-descriptions-item label="成本价">¥{{ detailData.costPrice || 0 }}</el-descriptions-item>
      <el-descriptions-item label="销量">{{ detailData.salesCount || 0 }}</el-descriptions-item>
      <el-descriptions-item label="条码">{{ detailData.barCode || '-' }}</el-descriptions-item>
      <el-descriptions-item label="图片" :span="2">
        <el-image
          v-if="detailData.picUrl"
          :src="detailData.picUrl"
          :preview-src-list="[detailData.picUrl]"
          class="w-100px h-100px"
          fit="cover"
        />
        <span v-else class="text-gray-400">暂无图片</span>
      </el-descriptions-item>
      <el-descriptions-item label="完整规格" :span="2">
        <el-tag
          v-for="(prop, index) in detailData.properties"
          :key="index"
          class="mr-5px"
          size="small"
        >
          {{ prop.propertyName }}: {{ prop.valueName }}
        </el-tag>
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="detailVisible = false">关 闭</el-button>
    </template>
  </Dialog>

  <!-- 图文详情查看弹窗 -->
  <Dialog v-model="descriptionVisible" title="图文详情" width="800px">
    <div v-html="currentDescription" class="p-20px max-h-600px overflow-y-auto"></div>
    <template #footer>
      <el-button @click="descriptionVisible = false">关 闭</el-button>
    </template>
  </Dialog>

  <!-- 预警设置弹窗 -->
  <Dialog v-model="warningVisible" title="库存预警设置" width="500px">
    <el-form ref="warningFormRef" :model="warningForm" label-width="100px">
      <el-form-item label="SKU信息">
        <el-tag>{{ warningForm.type }}</el-tag>
        <el-tag class="ml-5px">{{ warningForm.secondLevel }}</el-tag>
        <el-tag class="ml-5px">{{ warningForm.thirdLevel }}</el-tag>
      </el-form-item>
      <el-form-item label="当前库存">
        <span>{{ warningForm.stock }}</span>
      </el-form-item>
      <el-form-item label="预警值" required>
        <el-input-number
          v-model="warningForm.alertStock"
          :min="0"
          class="!w-full"
          placeholder="请设置库存预警值"
        />
      </el-form-item>
      <el-alert title="当库存低于预警值时，系统将发出提醒" type="info" :closable="false" />
    </el-form>
    <template #footer>
      <el-button @click="warningVisible = false">取 消</el-button>
      <el-button type="primary" :loading="warningSaving" @click="handleSaveWarning"
        >保 存</el-button
      >
    </template>
  </Dialog>

  <!-- 生成卡片弹窗 -->
  <Dialog v-model="generateVisible" title="生成卡片" width="500px">
    <el-form ref="generateFormRef" :model="generateForm" :rules="generateRules" label-width="100px">
      <el-form-item label="SKU信息">
        <el-tag>{{ generateForm.type }}</el-tag>
        <el-tag class="ml-5px">{{ generateForm.secondLevel }}</el-tag>
        <el-tag class="ml-5px">{{ generateForm.thirdLevel }}</el-tag>
      </el-form-item>
      <el-form-item label="当前库存">
        <span>{{ generateForm.stock }}</span>
      </el-form-item>
      <el-form-item label="生成数量" prop="count" required>
        <el-input-number
          v-model="generateForm.count"
          :min="1"
          :max="10000"
          class="!w-full"
          placeholder="请输入生成数量"
        />
      </el-form-item>
      <el-alert title="生成后将自动更新库存并创建对应数量的卡片" type="info" :closable="false" />
    </el-form>
    <template #footer>
      <el-button @click="generateVisible = false">取 消</el-button>
      <el-button type="primary" :loading="generating" @click="handleConfirmGenerate"
        >确 定</el-button
      >
    </template>
  </Dialog>

  <!-- 实体卡录入弹窗 -->
  <Dialog v-model="inputCardVisible" title="实体卡录入" width="700px">
    <el-form ref="inputCardFormRef" :model="inputCardForm" label-width="120px">
      <el-form-item label="选择SKU" required>
        <el-select
          v-model="inputCardForm.selectedSkuId"
          placeholder="请选择要录入的实体卡SKU"
          class="!w-full"
          @change="handleSkuChange"
        >
          <el-option
            v-for="sku in physicalCardSkuList"
            :key="sku.id"
            :label="`${sku.type} - ${sku.secondLevel} - ${sku.thirdLevel}`"
            :value="sku.id"
          >
            <div class="flex items-center justify-between">
              <span>{{ sku.type }} - {{ sku.secondLevel }} - {{ sku.thirdLevel }}</span>
              <el-tag size="small" type="info">库存: {{ sku.stock }}</el-tag>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上传实体卡图片" required>
        <UploadImg
          v-model="inputCardForm.imageUrl"
          :limit="1"
          @update:model-value="handleImageUpload"
        />
        <div class="text-gray-400 text-sm mt-5px">
          请上传清晰的实体卡图片，系统将自动识别卡号和卡密信息
        </div>
      </el-form-item>

      <!-- 识别结果区域 -->
      <el-divider v-if="recognitionResult" content-position="left">识别结果</el-divider>

      <template v-if="recognitionResult">
        <el-alert
          v-if="recognitionResult.success"
          title="识别成功！请核对以下信息"
          type="success"
          :closable="false"
          class="mb-15px"
        />
        <el-alert
          v-else
          title="识别失败，请手动输入卡片信息"
          type="warning"
          :closable="false"
          class="mb-15px"
        />

        <el-form-item label="卡号" required>
          <el-input v-model="inputCardForm.cardNumber" placeholder="请输入或识别卡号" clearable>
            <template #prepend>
              <el-tag>{{ recognitionResult.success ? '已识别' : '手动输入' }}</el-tag>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="卡密" required>
          <el-input v-model="inputCardForm.cardPassword" placeholder="请输入或识别卡密" clearable>
            <template #prepend>
              <el-tag>{{ recognitionResult.success ? '已识别' : '手动输入' }}</el-tag>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="识别置信度" v-if="recognitionResult.success">
          <el-progress
            :percentage="recognitionResult.confidence || 0"
            :color="recognitionResult.confidence > 80 ? '#67c23a' : '#e6a23c'"
          />
        </el-form-item>
      </template>

      <el-alert title="录入后将自动创建卡片记录并更新库存" type="info" :closable="false" />
    </el-form>
    <template #footer>
      <el-button @click="inputCardVisible = false">取 消</el-button>
      <el-button
        type="primary"
        :loading="inputCardSaving"
        :disabled="!canSubmitInputCard"
        @click="handleConfirmInputCard"
      >
        确认录入
      </el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import * as SpuApi from '@/api/mall/product/spu'
import * as CardApi from '@/api/system/deliveryCard/card'
import { UploadImg } from '@/components/UploadFile'
import { Editor } from '@/components/Editor'
import { DICT_TYPE } from '@/utils/dict'
import { ElMessageBox } from 'element-plus'

defineOptions({ name: 'DeliveryCardInventory' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const list = ref<any[]>([]) // 原始SKU列表
const filterList = ref<any[]>([]) // 过滤后的列表
const queryParams = reactive({
  type: undefined,
  secondLevel: undefined,
  thirdLevel: undefined
})
const queryFormRef = ref() // 搜索的表单

// 编辑相关
const editVisible = ref(false)
const editForm = ref<any>({})
const editFormRef = ref()
const saving = ref(false)
const currentSpu = ref<any>(null) // 当前的SPU数据

// 详情相关
const detailVisible = ref(false)
const detailData = ref<any>({})

// 图文详情查看相关
const descriptionVisible = ref(false)
const currentDescription = ref('')

// 预警设置相关
const warningVisible = ref(false)
const warningForm = ref<any>({})
const warningFormRef = ref()
const warningSaving = ref(false)

// 生成卡片相关
const generateVisible = ref(false)
const generateForm = ref<any>({})
const generateFormRef = ref()
const generating = ref(false)
const generateRules = {
  count: [
    { required: true, message: '请输入生成数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ]
}

// 实体卡录入相关
const inputCardVisible = ref(false)
const inputCardForm = ref<any>({})
const inputCardFormRef = ref()
const inputCardSaving = ref(false)
const recognitionResult = ref<any>(null)
const physicalCardSkuList = ref<any[]>([]) // 实体卡类型的SKU列表

// 计算属性：是否可以提交实体卡录入
const canSubmitInputCard = computed(() => {
  return (
    inputCardForm.value.selectedSkuId &&
    inputCardForm.value.imageUrl &&
    inputCardForm.value.cardNumber &&
    inputCardForm.value.cardPassword
  )
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 1. 查询 spuType=1 的SPU
    const spuData: any = await SpuApi.getSpuPage({ pageNo: 1, pageSize: 100, spuType: 1 } as any)
    const spuList = spuData.list || []

    if (spuList.length === 0) {
      message.warning('未找到配送卡类型的SPU（spuType=1）')
      list.value = []
      filterList.value = []
      return
    }

    // 2. 获取第一条SPU（应该只有一条）
    const spu = spuList[0]

    // 3. 获取SPU详情（包含SKU数据）
    const spuDetail = await SpuApi.getSpu(spu.id)
    currentSpu.value = spuDetail // 保存完整的SPU数据（包含skus）
    const skus = spuDetail.skus || []

    // 4. 前端拆分规格，转换为表格数据
    const tableData = skus.map((sku: any) => {
      const properties = sku.properties || []

      // 提取三层分类（按照数组顺序）
      const type = properties[0]?.valueName || '-' // 第一层：类型
      const secondLevel = properties[1]?.valueName || '-' // 第二层：二级分类
      const thirdLevel = properties[2]?.valueName || '-' // 第三层：三级分类

      return {
        ...sku,
        spuId: spu.id, // 确保spuId字段存在
        type,
        secondLevel,
        thirdLevel
      }
    })

    list.value = tableData
    filterList.value = tableData

    // 筛选出实体卡类型的SKU供录入使用
    physicalCardSkuList.value = tableData.filter((item: any) => item.type === '实体卡')

    // 检查库存预警
    checkStockWarning(tableData)
  } catch (error) {
    console.error('查询失败:', error)
    message.error('查询失败')
  } finally {
    loading.value = false
  }
}

/** 检查库存预警 */
const checkStockWarning = (data: any[]) => {
  const lowStockItems = data.filter((item) => {
    return (
      item.stockWarning !== null &&
      item.stockWarning !== undefined &&
      item.stock < item.stockWarning
    )
  })

  if (lowStockItems.length > 0) {
    const messages = lowStockItems.map((item) => {
      return `${item.type}-${item.secondLevel}-${item.thirdLevel}库存不足，请尽快补充！`
    })

    // 使用警告消息显示库存不足提醒
    messages.forEach((msg) => {
      message.warning(msg)
    })
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  // 前端过滤
  filterList.value = list.value.filter((item) => {
    let match = true
    if (queryParams.type) {
      match = match && item.type.includes(queryParams.type)
    }
    if (queryParams.secondLevel) {
      match = match && item.secondLevel.includes(queryParams.secondLevel)
    }
    if (queryParams.thirdLevel) {
      match = match && item.thirdLevel.includes(queryParams.thirdLevel)
    }
    return match
  })
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  filterList.value = list.value
}

/** 编辑 */
const handleEdit = (row: any) => {
  editForm.value = { ...row }
  editVisible.value = true
}

/** 保存编辑 */
const handleSave = async () => {
  if (!currentSpu.value) {
    message.error('未找到SPU数据')
    return
  }

  // 确保 skus 数组存在
  if (!currentSpu.value.skus) {
    currentSpu.value.skus = []
  }

  saving.value = true
  try {
    // 1. 找到当前编辑的SKU在原始数据中的位置
    const skuIndex = currentSpu.value.skus.findIndex((sku: any) => sku.id === editForm.value.id)

    if (skuIndex === -1) {
      // 如果是新SKU（没有id），添加到数组中
      currentSpu.value.skus.push({
        ...editForm.value,
        spuId: currentSpu.value.id
      })
    } else {
      // 更新现有SKU
      currentSpu.value.skus[skuIndex] = {
        ...currentSpu.value.skus[skuIndex],
        stock: editForm.value.stock,
        price: editForm.value.price,
        marketPrice: editForm.value.marketPrice,
        costPrice: editForm.value.costPrice,
        picUrl: editForm.value.picUrl,
        description: editForm.value.description
      }
    }

    // 2. 更新整个SPU（包含所有SKU）
    await SpuApi.updateSpu(currentSpu.value)

    message.success('保存成功')
    editVisible.value = false

    // 3. 刷新列表
    await getList()
  } catch (error) {
    console.error('保存失败:', error)
    message.error('保存失败')
  } finally {
    saving.value = false
  }
}

/** 查看详情 */
const handleViewDetail = (row: any) => {
  detailData.value = row
  detailVisible.value = true
}

/** 查看图文详情 */
const handleViewDescription = (row: any) => {
  currentDescription.value = row.description || ''
  descriptionVisible.value = true
}

/** 预警设置 */
const handleWarning = (row: any) => {
  warningForm.value = { ...row }
  warningVisible.value = true
}

/** 删除 */
const handleDelete = async (row: any) => {
  try {
    // 二次确认
    await ElMessageBox.confirm(
      `确定要删除 ${row.type}-${row.secondLevel}-${row.thirdLevel} 这个SKU吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 执行删除
    await SpuApi.deleteSku(row.id)
    message.success('删除成功')

    // 刷新列表
    await getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      message.error('删除失败')
    }
  }
}

/** 保存预警设置 */
const handleSaveWarning = async () => {
  warningSaving.value = true
  try {
    const skuId = warningForm.value.id
    if (!skuId) {
      message.error('未找到SKU编号')
      return
    }

    // 直接调用SKU更新接口
    await SpuApi.updateSku(skuId, {
      stockWarning: warningForm.value.alertStock
    })

    message.success('预警设置成功')
    warningVisible.value = false

    // 刷新列表
    await getList()
  } catch (error) {
    console.error('预警设置失败:', error)
    message.error('预警设置失败')
  } finally {
    warningSaving.value = false
  }
}

/** 生成卡片 */
const handleGenerateCard = (row: any) => {
  generateForm.value = { ...row, count: undefined }
  generateVisible.value = true
}

/** 生成唯一随机数字 */
const generateUniqueRandomNumber = (length: number, existingSet: Set<string>): string => {
  let num: string
  do {
    num = ''
    for (let i = 0; i < length; i++) {
      num += Math.floor(Math.random() * 10)
    }
  } while (existingSet.has(num))
  existingSet.add(num)
  return num
}

/** 确认生成卡片 */
const handleConfirmGenerate = async () => {
  // 表单验证
  if (!generateFormRef.value) return
  await generateFormRef.value.validate()

  generating.value = true
  try {
    const count = generateForm.value.count
    const skuId = generateForm.value.id
    const spuId = generateForm.value.spuId
    const currentStock = generateForm.value.stock || 0
    const cardType = generateForm.value.type

    if (!skuId || !spuId) {
      message.error('SKU或SPU信息不完整')
      return
    }

    // 第一步：生成卡片数据
    const cardNumberSet = new Set<string>()
    const cardPasswordSet = new Set<string>()

    // 确定卡号前缀和类型值
    let cardPrefix = ''
    let typeValue = 0
    if (cardType === '电子卡') {
      cardPrefix = 'DZ'
      typeValue = 1
    } else if (cardType === '实体卡') {
      cardPrefix = 'ST'
      typeValue = 2
    } else {
      message.error('无法识别的卡片类型')
      return
    }

    // 批量生成卡片数据
    const cardList: CardApi.CardSaveReqVO[] = []
    for (let i = 0; i < count; i++) {
      const cardNumber = cardPrefix + generateUniqueRandomNumber(8, cardNumberSet)
      const cardPassword = 'sjgy' + generateUniqueRandomNumber(6, cardPasswordSet)

      cardList.push({
        spuId: spuId,
        skuId: skuId,
        cardNumber: cardNumber,
        cardPassword: cardPassword,
        type: typeValue,
        status: 0
      })
    }

    // 第二步：批量创建卡片（先创建卡片）
    await CardApi.batchCreateCard(cardList)

    // 第三步：卡片创建成功后，再更新库存（当前库存 + 生成数量）
    const newStock = currentStock + count
    await SpuApi.updateSku(skuId, {
      stock: newStock
    })

    message.success(`成功生成${count}张卡片`)
    generateVisible.value = false

    // 刷新列表
    await getList()
  } catch (error) {
    console.error('生成卡片失败:', error)
    message.error('生成卡片失败')
  } finally {
    generating.value = false
  }
}

/** 实体卡录入 */
const handleInputPhysicalCard = () => {
  // 检查是否有实体卡类型的SKU
  if (physicalCardSkuList.value.length === 0) {
    message.warning('暂无实体卡类型的SKU，无法录入')
    return
  }

  // 重置表单和识别结果
  inputCardForm.value = {
    selectedSkuId: undefined,
    imageUrl: undefined,
    cardNumber: undefined,
    cardPassword: undefined
  }
  recognitionResult.value = null
  inputCardVisible.value = true
}

/** SKU选择变化 */
const handleSkuChange = (skuId: number) => {
  const selectedSku = physicalCardSkuList.value.find((sku: any) => sku.id === skuId)
  if (selectedSku) {
    inputCardForm.value = {
      ...inputCardForm.value,
      ...selectedSku,
      selectedSkuId: skuId
    }
  }
}

/** 图片上传后处理 */
const handleImageUpload = async (imageUrl: string) => {
  if (!imageUrl) {
    recognitionResult.value = null
    return
  }

  message.info('正在识别卡片信息...')

  try {
    // TODO: 调用OCR识别接口
    // const result = await CardApi.recognizeCard({ imageUrl })

    // 模拟识别结果（接口预留）
    setTimeout(() => {
      // 模拟识别成功的情况
      const mockSuccess = Math.random() > 0.3 // 70% 成功率

      if (mockSuccess) {
        const mockCardNumber = 'ST' + Math.random().toString().slice(2, 10)
        const mockCardPassword = 'sjgy' + Math.random().toString().slice(2, 8)

        recognitionResult.value = {
          success: true,
          cardNumber: mockCardNumber,
          cardPassword: mockCardPassword,
          confidence: Math.floor(Math.random() * 20) + 80 // 80-100
        }

        // 填充识别结果到表单
        inputCardForm.value.cardNumber = mockCardNumber
        inputCardForm.value.cardPassword = mockCardPassword

        message.success('识别成功！')
      } else {
        // 识别失败，允许手动输入
        recognitionResult.value = {
          success: false,
          message: '图片质量不佳或无法识别，请手动输入'
        }

        message.warning('自动识别失败，请手动输入卡片信息')
      }
    }, 1500)
  } catch (error) {
    console.error('识别失败:', error)
    recognitionResult.value = {
      success: false,
      message: '识别服务异常，请手动输入'
    }
    message.error('识别失败，请手动输入卡片信息')
  }
}

/** 确认录入实体卡 */
const handleConfirmInputCard = async () => {
  if (!inputCardForm.value.selectedSkuId) {
    message.error('请选择SKU')
    return
  }

  if (!inputCardForm.value.cardNumber || !inputCardForm.value.cardPassword) {
    message.error('请填写完整的卡号和卡密信息')
    return
  }

  inputCardSaving.value = true
  try {
    const skuId = inputCardForm.value.selectedSkuId
    const spuId = inputCardForm.value.spuId
    const currentStock = inputCardForm.value.stock || 0

    if (!skuId || !spuId) {
      message.error('SKU或SPU信息不完整，请重新选择')
      return
    }

    // TODO: 检查卡号是否已存在
    // const exists = await CardApi.checkCardExists({ cardNumber: inputCardForm.value.cardNumber })
    // if (exists) {
    //   message.error('该卡号已存在，请检查')
    //   return
    // }

    // 创建卡片记录
    const cardData: CardApi.CardSaveReqVO = {
      spuId: spuId,
      skuId: skuId,
      cardNumber: inputCardForm.value.cardNumber,
      cardPassword: inputCardForm.value.cardPassword,
      type: 2, // 实体卡
      status: 0, // 未使用
      imageUrl: inputCardForm.value.imageUrl // 保存卡片图片
    }

    // 调用创建接口
    await CardApi.createCard(cardData)

    // 更新库存（当前库存 + 1）
    const newStock = currentStock + 1
    await SpuApi.updateSku(skuId, {
      stock: newStock
    })

    message.success('实体卡录入成功')
    inputCardVisible.value = false

    // 刷新列表
    await getList()
  } catch (error) {
    console.error('录入失败:', error)
    message.error('录入失败，请重试')
  } finally {
    inputCardSaving.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
